package com.sddm.printServer.endpoint;

import com.sddm.printServer.coder.CallBackDecoder;
import com.sddm.printServer.coder.CallBackEncoder;
import com.sddm.printServer.coder.PrintDecoder;
import com.sddm.printServer.coder.PrintEncoder;
import com.sddm.printServer.entiy.CallBack;
import com.sddm.printServer.entiy.Print;
import com.sddm.printServer.enums.CallBackEnum;
import com.sddm.printServer.service.impl.DefaultResponseAdapterImpl;
import com.sddm.printServer.service.impl.SocketMessageAdapterImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wyh
 * @version 1.0
 * @date 2022/4/6 17:00
 */
@Component
@ServerEndpoint(value = "/localClient/{customerId}",
        decoders = {PrintDecoder.class, CallBackDecoder.class},
        encoders = {PrintEncoder.class, CallBackEncoder.class})
public class SocketServer {
    private static ApplicationContext applicationContext;

    //为这个变量添加set方法
    public static void setApplicationContext(ApplicationContext applicationContext) {
        SocketServer.applicationContext = applicationContext;
    }

    private static final Logger log = LoggerFactory.getLogger(SocketServer.class);


    /**
     * 记录当前在线连接数
     */
    public static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("customerId") String customerId) {
        sessionMap.put(customerId, session);
        log.warn("{}连接成功,连接数是{}", customerId, sessionMap.size());
        try {
            CallBack callBack = applicationContext.getBean(SocketMessageAdapterImpl.class).onOpenProcess(customerId, session);
            applicationContext.getBean(DefaultResponseAdapterImpl.class).sendMessage(callBack, session);
        } catch (Exception e) {
            log.error(String.valueOf(e));
            applicationContext.getBean(DefaultResponseAdapterImpl.class).sendMessage(new CallBack(CallBackEnum.FAILURE.getCode()
                    ,customerId,CallBackEnum.FAILURE.getMessage()),session);
        }

    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("customerId") String customerId) {
        sessionMap.remove(customerId);
        log.warn("{}掉线了,当前连接数是{}", customerId, sessionMap.size());
    }

    /**
     * 收到客户端消息后调用的方法
     * 后台收到客户端发送过来的消息
     * onMessage 是一个消息的中转站
     * 接受 浏览器端 socket.send 发送过来的 json数据
     */
    @OnMessage
    public void onMessage(List<Print> print, Session session, @PathParam("customerId") String customerId) {
        log.warn("接受到{}的消息为：{}", customerId, print);
        applicationContext.getBean(SocketMessageAdapterImpl.class).onMessageProcess(print, session);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }


}
